package com.dhwl.hsh.driver.ui.fragment;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.dhwl.hsh.driver.R;
import com.dhwl.hsh.driver.presenter.MainPresenter;
import com.dhwl.hsh.driver.presenter.OrderPresenter;
import com.dhwl.hsh.driver.presenter.iview.IGetTasksView;
import com.dhwl.hsh.driver.ui.activity.BaseActivity;
import com.dhwl.hsh.driver.ui.adapter.ListPopupWindowAdapter;
import com.dhwl.hsh.driver.ui.adapter.TaskListAdapter;
import com.dhwl.hsh.lib.bean.resp.OrderListResponse;
import com.dhwl.hsh.lib.core.HshException;
import com.dhwl.hsh.lib.utils.SystemTool;
import com.dhwl.hsh.lib.utils.ToastUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 货源大厅
 *
 * @author Derek.Kidd
 * @time 2016/4/20 9:44
 */
public class HomeFragment extends BaseFragment implements IGetTasksView {

    @Bind(R.id.tv_truck_type)
    TextView tvTruckType;
    @Bind(R.id.tv_start_ship)
    TextView tvStartShip;
    @Bind(R.id.tv_task_type)
    TextView tvTaskType;
    @Bind(R.id.pull_refresh_list)
    PullToRefreshListView pullRefreshList;
    @Bind(R.id.pic_empty)
    ImageView picEmpty;
    @Bind(R.id.tv_empty)
    TextView tvEmpty;

    private TaskListAdapter taskListAdapter;
    private List<OrderListResponse> orderListResps;

    private ArrayList<String> mArrayList;

    private ListPopupWindowAdapter listPopupWindowAdapter;

    private PopupWindow popupWindow;

    MainPresenter mainPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected void initViews(View self, Bundle savedInstanceState) {
        setTitleContent(R.string.function_bar_home);

    }

    @Override
    protected void initData() {

        mainPresenter = new MainPresenter();
        mainPresenter.attachView(this);

        orderListResps = new ArrayList<>();
        orderListResps.add(new OrderListResponse());
        orderListResps.add(new OrderListResponse());
        taskListAdapter = new TaskListAdapter(getActivity(), orderListResps);
        pullRefreshList.setAdapter(taskListAdapter);


        pullRefreshList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(8000);
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    pullRefreshList.onRefreshComplete();
                                }
                            });
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

            }
        });
        mArrayList = new ArrayList<String>();
        listPopupWindowAdapter = new ListPopupWindowAdapter(getActivity(), mArrayList);

        initPopWindow();
    }


    @OnClick({R.id.tv_truck_type, R.id.tv_start_ship, R.id.tv_task_type})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_truck_type:
                //listPopupWindowAdapter.setCheckPosition(2);
                mArrayList.clear();
                String[] trucks = getResources().getStringArray(R.array.truck_title);
                mArrayList.add("全部");
                mArrayList.add(trucks[0]);
                mArrayList.add(trucks[1]);
                mArrayList.add(trucks[2]);
                mArrayList.add(trucks[3]);
                showPopupWindow(view);
                break;
            case R.id.tv_start_ship:
                //TODO
                showPopupWindow(view);
                break;
            case R.id.tv_task_type:
                mArrayList.clear();
                mArrayList.add("全部");
                mArrayList.add("单次");
                mArrayList.add("长期");
                showPopupWindow(view);
                break;
            default:
                hidePopupWindow();
                break;
        }

    }

    /**
     * 初始化PopupWindow
     */
    private void initPopWindow() {
        LayoutInflater inflater = (LayoutInflater) getActivity()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View conentView = inflater.inflate(R.layout.popupwindow_list, null);

        conentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });
        ListView listView = (ListView) conentView.findViewById(R.id.listView_popupWindow);
        listView.setAdapter(listPopupWindowAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //TODO
                ToastUtils.show(getActivity(), "" + position, Toast.LENGTH_SHORT);
                hidePopupWindow();
            }
        });

        int h = getActivity().getWindowManager().getDefaultDisplay().getHeight();
        int w = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        popupWindow = new PopupWindow(getActivity());
        // 设置SelectPicPopupWindow的View
        popupWindow.setContentView(conentView);
        // 设置SelectPicPopupWindow弹出窗体的宽
        popupWindow.setWidth(w);
        // 设置SelectPicPopupWindow弹出窗体的高
        int height = ((BaseActivity) getActivity()).mTintManager.getConfig().getNavigationBarHeight() + ((BaseActivity) getActivity()).mTintManager.getConfig().getStatusBarHeight();
        popupWindow.setHeight(h - SystemTool.dp2px(getActivity(), 100) + height);
        // 设置SelectPicPopupWindow弹出窗体可点击
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        // 刷新状态
        popupWindow.update();
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable();
        dw.setAlpha(76);
        // 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
        popupWindow.setBackgroundDrawable(dw);

        // 设置SelectPicPopupWindow弹出窗体动画效果
//      popupWindow.setAnimationStyle(R.style.AnimationPopup);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popupWindow = null;
            }
        });
    }

    /**
     * 显示PopupWindow
     *
     * @param view
     */
    private void showPopupWindow(View view) {
        if (null == popupWindow) {
            initPopWindow();
        }
        if (!popupWindow.isShowing()) {
            // 以下拉方式显示popupwindow
            popupWindow.showAsDropDown(view, view.getLayoutParams().width / 2, 1);
        } else {
            popupWindow.dismiss();
        }
    }

    /**
     * 隐藏PopupWindow
     */
    private void hidePopupWindow() {
        if (popupWindow != null && popupWindow.isShowing())
            popupWindow.dismiss();
    }

    @Override
    public void onGetTasksFailure(HshException e) {

    }

    @Override
    public void onGetTasksSuccess(Object object) {

    }

}
